package com.ruoyi.dm.component;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import com.ruoyi.common.utils.biz.BizModule;
import com.ruoyi.common.utils.biz.PathUtil;
import com.ruoyi.dm.component.manager.DensityDataManager;
import com.ruoyi.dm.domain.BO.ResReturnBO;
import com.ruoyi.dm.domain.po.AirCollectRecordPO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.FileReader;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 空间 密度数据策略 apod星
 */
@Component
@Slf4j
public class ApodDataStrategy implements DataStrategy<AirCollectRecordPO> {

    @Autowired
    DensityDataManager densityDataManager;

    @Override
    public AirCollectRecordPO makeupPo(AirCollectRecordPO po) {
        //ato_20190101.dat
        String fileName = po.getFileName();
        String[] split = fileName.split("_|\\.");
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        LocalDate parse = LocalDate.parse(split[1], formatter);
        po.setFileDate(parse);
        return po;
    }


    @Override
    public String pythonCmd(String satellite, String dataType, String filePath, String method, Integer year) {
        return null;
    }

    @Override
    public void save(String satellite, String outFile) throws Exception {
        densityDataManager.saveApodData(satellite,outFile);
    }

    /**
     * 解析apod星.
     * @param file
     * @return
     */
    @Override
    public ResReturnBO analysis(String file) throws Exception {
        ResReturnBO resReturnBO = new ResReturnBO();
        BufferedReader acc = new BufferedReader(new FileReader(file));
        int count = 0;
        //异常数据
        int numError = 0;
        String logFile = PathUtil.outputModuleDir(BizModule.COLLECT) + "/apod/" + UUID.fastUUID().toString(true) + ".log";
        List<String> logTmpLines = new ArrayList<>();
        List<String> logLines = new ArrayList<>();
        String line = "";

        try {
            // UTC,纬度,经度,高度,地方时,探测密度,MSISE密度  58849
            // 58484.0000810     70.1854    281.3566    445.8746 18.7590    .2573443374574365E-12    .1818730880196509E-12
            Set<String> timeSet = new HashSet<>();
            while (null != (line = acc.readLine())) {
                String[] split = line.split("\\s+");
                String timeStr = split[1];
                if (timeSet.contains(timeStr)) {
                    log.info("重复时间:{}", timeStr);
                    numError++;
                    logTmpLines.add(line);
                } else {
                    count++;
                    timeSet.add(timeStr);
                }
            }
            log.info("{} size:{}", file, count);
            resReturnBO.setCode(1);
        }catch (Exception e) {
            resReturnBO.setCode(0);
            resReturnBO.setMsg(e.getMessage());
            log.error("{} 解析失败", file, e);
        }finally{
            acc.close();
        }
        resReturnBO.setTotal(count);
        resReturnBO.setError(numError);
        resReturnBO.setOutFile(file);
        //[数据总条数为33925个, 异常值的数量为100个，所有异常数据均已剔除]
        logLines.add(String.format("[数据总条数为%d个,异常值的数量为%d个，所有异常数据均已忽略]",count+numError,numError));
        logLines.add("重复数据如下:");
        logLines.addAll(2,logTmpLines);
        FileUtil.writeLines(logLines,logFile,"utf-8");
        resReturnBO.setLogFile(logFile);
        return resReturnBO;
    }
}
